<template>
	<div>
		<el-card shadow="hover">
			<div class=" mb15">
				<el-form :model="tableData.param" ref="queryRef" :inline="true" label-width="120px">
					<el-row>
						<el-col :span="8" class="colBlock">
							<el-form-item label="注册时间">
								<el-date-picker v-model="tableData.dateRange" type="datetimerange" size="default"
									style="width: 300px" range-separator="-" start-placeholder="开始日期"
									end-placeholder="结束日期"></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :span="8" class="colBlock">
							<el-form-item label="认证时间">
								<el-date-picker v-model="tableData.dateRangeAuth" type="datetimerange" size="default"
									style="width: 300px" range-separator="-" start-placeholder="开始日期"
									end-placeholder="结束日期"></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :span="8" :class="showAll ? 'colBlock' : 'colNone'">
							<el-form-item label="企业名称" prop="companyName">
								<el-input v-model="tableData.param.companyName" placeholder="请输入企业名称" clearable
									@keyup.enter.native="getList" />
							</el-form-item>
						</el-col>
						<el-col :span="8" :class="showAll ? 'colBlock' : 'colNone'">
							<el-form-item label="状态" prop="statuses">
								<el-select v-model="tableData.param.statuses" placeholder="请选择状态" clearable multiple>
									<el-option v-for="item in dictionary.statusList2" :label="item.label" :value="item.value"
										:key="item.value" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="8" :class="!showAll ? 'colBlock' : 'colNone'">
							<el-form-item>
								<el-button type="primary" @click="getList"><el-icon>
										<Search />
									</el-icon>搜索</el-button>
								<el-button @click="resetQuery(queryRef)"><el-icon>
										<Refresh />
									</el-icon>重置</el-button>
								<el-button type="primary" link @click="toggleSearch">
									{{ word }}
									<el-icon v-show="showAll">
										<ArrowUp />
									</el-icon>
									<el-icon v-show="!showAll">
										<ArrowDown />
									</el-icon>
								</el-button>
							</el-form-item>
						</el-col>
						<el-col :span="8" :class="showAll ? 'colBlock' : 'colNone'">
							<el-form-item>
								<el-button type="primary" @click="getList"><el-icon>
										<Search />
									</el-icon>搜索</el-button>
								<el-button @click="resetQuery(queryRef)"><el-icon>
										<Refresh />
									</el-icon>重置</el-button>
								<el-button type="primary" link @click="toggleSearch">
									{{ word }}
									<el-icon v-show="showAll"><ArrowUp /></el-icon>
									<el-icon v-show="!showAll"><ArrowDown /></el-icon>
								</el-button>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
				<el-row :gutter="10" class="mb8" v-if="permissionStore.isPermissionsBtn('002002001')">
					<el-col :span="1.5">
						<el-button type="primary" @click="exportFile"><el-icon>
								<Download />
							</el-icon> 导出</el-button>
					</el-col>
				</el-row>
			</div>
			<el-table v-loading="loading" :data="tableData.data">
				<el-table-column label="企业名称" align="center" prop="companyName" min-width="200px" />
				<el-table-column label="经办人" align="center" prop="handName" min-width="100px" />
				<el-table-column label="联系方式" align="center" prop="handPhone" min-width="100px" />
				<el-table-column label="累计充值金额" align="center" prop="totalAmount" min-width="100px" />
				<el-table-column label="剩余金额" align="center" prop="balance" min-width="100px" />
				<el-table-column label="卡数量" align="center" prop="simCardCount" min-width="100px" />
				<el-table-column label="坐席数量" align="center" prop="seatCount" min-width="100px" />
				<el-table-column label="月租" align="center" prop="monthPrice" min-width="100px" />
				<el-table-column label="状态" align="center" prop="companyAuthStatus" min-width="100px" >
					<template #default="{row}">{{ dictionary[row.companyAuthStatus] }}</template>
				</el-table-column>
				<el-table-column label="注册时间" align="center" min-width="150px">
					<template #default="scope">
						{{ formatDateTime(scope.row.registerTime) }}
					</template>
				</el-table-column>
				<el-table-column label="认证时间" align="center" min-width="150px">
					<template #default="scope">
						{{ formatDateTime(scope.row.authTime) }}
					</template>
				</el-table-column>
				<el-table-column label="操作"  align="center" class-name="small-padding" min-width="200px" fixed="right" v-if="permissionStore.isPermissionsBtn(['002002002','002002003','002002004'])">
					<template #default="scope">
						<el-button type="primary" link @click="handleView(scope.row)" v-if="permissionStore.isPermissionsBtn('002002002')"><el-icon>
								<View />
							</el-icon>详情</el-button>
						<el-button v-if="scope.row.outCallStatus && permissionStore.isPermissionsBtn('002002003')" type="danger" link @click="closeCallout(scope.row)" ><el-icon>
								<Edit />
							</el-icon>关闭外呼</el-button>	
						<el-button v-if="!scope.row.outCallStatus && permissionStore.isPermissionsBtn('002002004')" type="primary" link @click="openCallout(scope.row)" ><el-icon>
								<Edit />
							</el-icon>开通外呼</el-button>		
					</template>
				</el-table-column>
			</el-table>
			<pagination v-show="tableData.total > 0" :total="tableData.total" v-model:page="tableData.param.pageNumber"
				v-model:limit="tableData.param.pageLength" @pagination="getList" />
		</el-card>
		<detailView ref="detailRef" @getList="getList"></detailView>
	</div>
</template>
<script lang="ts">
import { companyListRealApi,closeCalloutApi,openCalloutApi } from '@/api/enterpriseManage/enterpriseAuthentication';
import { toRefs, reactive, onMounted, ref, defineComponent, computed, getCurrentInstance, toRaw } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { usePermissionStore } from "@/store/modules/permission"
import { getFile } from '@/utils/excel/excelUtil'
import dictionary from '@/utils/dictionary.json'
import detailView from './component/detail.vue';
import { dateToTimestamp, formatDateTime } from '@/utils/index'
export default defineComponent({
	name: 'enterpriseAuthenticationList', //已认证企业列表
	components: {
		detailView,
	},
	setup() {
		const { proxy } = <any>getCurrentInstance();
		const loading = ref(false);
		const queryRef = ref();
		const detailRef = ref();
		const permissionStore = usePermissionStore()
		// 是否显示所有搜索选项
		const showAll = ref(false);

		const word = computed(() => {
			if (showAll.value === false) {
				//对文字进行处理
				return '展开搜索';
			} else {
				return '收起搜索';
			}
		});
		const state = reactive({
			ids: [],
			tableData: {
				data: [],
				total: 0,
				loading: false,
				dateRange: [],
				dateRangeAuth: [],	//认证时间
				param: {
					pageNumber: 1,
					pageLength: 10,
					registerBeginTime: null,
					registerEndTime: null,
					authBeginTime: null,
					authEndTime: null,
					companyName:null,
					statuses: [],
				},
			},
		});
		// 页面加载时
		onMounted(() => {
			initTableData();
		});
		// 初始化表格数据
		const initTableData = () => {
			getList();
		};
		/** 重置按钮登录 */
		const resetQuery = (formEl: FormInstance | undefined) => {
			if (!formEl) return;
			formEl.resetFields();
			state.tableData.dateRange = []
			state.tableData.dateRangeAuth = []
			getList();
		};
		// 获取列表数据
		const getList = () => {
			loading.value = true;

			const { dateRange, dateRangeAuth, param } = state.tableData;
			// 处理创建时间
			handleDateRange(dateRange, param, 'register');
			// 处理认证时间
			handleDateRange(dateRangeAuth, param, 'auth');

			companyListRealApi(state.tableData.param).then((res: any) => {
				let list = res.data.list ?? [];
				state.tableData.data = list
				console.log(state.tableData.data);
				state.tableData.total = res.data.total;
				loading.value = false;
			});
		};

		// 处理日期范围的通用函数
		const handleDateRange = (range, param, prefix) => {
			if (range && range.length === 2) {
				param[`${prefix}BeginTime`] = dateToTimestamp(range[0]);
				param[`${prefix}EndTime`] = dateToTimestamp(range[1]);
			} else {
				param[`${prefix}BeginTime`] = null;
				param[`${prefix}EndTime`] = null;
			}
		};

		const toggleSearch = () => {
			showAll.value = !showAll.value;
		};
		const handleView = (row) => {
			detailRef.value.openDialog(row.companyCode);
		}
		// 导出文件
		const exportFile = async () => {
			getFile('/system/company/company/real/export', '已人认证企业列表')
		}
		// 开通外呼
		const closeCallout=(row)=>{
			let msg = `此操作将关闭：“${row.companyName}”的外呼功能，是否继续?`
			ElMessageBox.confirm(msg, '提示', {
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(() => {
					closeCalloutApi({id:row.companyCode}).then(res=>{
						ElMessage.success(`关闭外呼功能成功`);
					getList();
					})
					
				})
				.catch(() => { });
		}
		// 开通
		const openCallout=(row)=>{
			ElMessageBox.prompt('请输入"' + row.companyName + '"的坐席数量', "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消"
			}).then(({ value }) => {
				if (!value || value == '') {
					ElMessage.error('坐席不能为空');
					return
				}
				let count=Number(value)
				if(count > 0 ) {
					openCalloutApi({ companyCode:row.companyCode, count }).then(() => {
					ElMessage.success(`开通外呼功能成功`);
					getList();
				});
				}else return ElMessage.error('请输入正确的数字')
				
			}).catch(() => { });
		}

		return {
			proxy,
			detailRef,
			showAll,
			loading,
			word,
			queryRef,
			permissionStore,
			resetQuery,
			getList,
			toggleSearch,
			exportFile,
			handleView,
			dictionary,
			formatDateTime,
			openCallout,
			closeCallout,
			...toRefs(state),
		};
	},
});
</script>
<style lang="scss" scoped>
.colBlock {
	display: block;
}

.colNone {
	display: none;
}
</style>
